"""
图形密码锁逻辑
"""
import time
from config.settings import PASSWORD_LOCK_CONFIG

class PasswordLock:
    def __init__(self, password_sequence):
        self.password_sequence = password_sequence  # 例: ["circle", "triangle", "square"]
        self.current_progress = 0
        self.last_check_time = 0
        self.check_interval = PASSWORD_LOCK_CONFIG["check_interval"]  # 检查间隔，避免重复识别
        self.max_attempts = PASSWORD_LOCK_CONFIG["max_attempts"]
        self.failed_attempts = 0
        self.lock_timeout = 0
        self.is_locked = False
        self.min_confidence = PASSWORD_LOCK_CONFIG["min_confidence_for_unlock"]
    
    def check_shapes(self, shapes):
        """检查输入的图形是否匹配密码序列"""
        current_time = time.time()
        
        # 检查是否被锁定
        if self.is_locked and current_time < self.lock_timeout:
            remaining_time = int(self.lock_timeout - current_time)
            return False, False, f"密码锁已被锁定，请等待 {remaining_time} 秒"
        elif self.is_locked and current_time >= self.lock_timeout:
            # 解除锁定
            self.is_locked = False
            self.failed_attempts = 0
        
        # 避免频繁检查
        if current_time - self.last_check_time < self.check_interval:
            return False, False, "请稍等..."
        
        self.last_check_time = current_time
        
        # 检查是否已完成所有密码
        if self.current_progress >= len(self.password_sequence):
            return True, True, "密码已完成！"
        
        # 获取当前需要的图形
        expected_shape = self.password_sequence[self.current_progress]
        
        # 查找期望的图形
        detected_shape = None
        for shape in shapes:
            if (shape["name"].lower() == expected_shape.lower() and 
                shape["confidence"] >= self.min_confidence):
                detected_shape = shape
                break
        
        if detected_shape:
            # 识别正确
            self.current_progress += 1
            self.failed_attempts = 0  # 重置失败次数
            
            if self.current_progress >= len(self.password_sequence):
                # 密码完成
                return True, True, "🎉 解锁成功！密码验证完成！"
            else:
                next_shape = self.password_sequence[self.current_progress]
                return True, False, f"✅ 正确！下一个图形: {self._get_shape_emoji(next_shape)}{next_shape}"
        else:
            # 识别错误或未识别到期望图形
            if shapes:
                detected_names = [shape["name"] for shape in shapes]
                wrong_input = ", ".join(detected_names)
            else:
                wrong_input = "未识别到图形"
            
            self.failed_attempts += 1
            
            if self.failed_attempts >= self.max_attempts:
                # 锁定系统
                self.is_locked = True
                self.lock_timeout = current_time + PASSWORD_LOCK_CONFIG["lock_timeout"]  # 锁定30秒
                self.reset()
                return False, False, f"❌ 错误次数过多！系统已锁定30秒。检测到: {wrong_input}"
            else:
                remaining_attempts = self.max_attempts - self.failed_attempts
                expected_emoji = self._get_shape_emoji(expected_shape)
                return False, False, f"❌ 错误！期望: {expected_emoji}{expected_shape}，检测到: {wrong_input}。剩余尝试次数: {remaining_attempts}"

    def check_input(self, image):
        """检查输入的图形是否匹配密码序列（已废弃，保留以保持向后兼容）"""
        from core.shape_detector import ShapeDetector
        detector = ShapeDetector()
        
        current_time = time.time()
        
        # 检查是否被锁定
        if self.is_locked and current_time < self.lock_timeout:
            remaining_time = int(self.lock_timeout - current_time)
            return False, False, f"密码锁已被锁定，请等待 {remaining_time} 秒"
        elif self.is_locked and current_time >= self.lock_timeout:
            # 解除锁定
            self.is_locked = False
            self.failed_attempts = 0
        
        # 避免频繁检查
        if current_time - self.last_check_time < self.check_interval:
            return False, False, "请稍等..."
        
        self.last_check_time = current_time
        
        # 获取当前需要的图形
        if self.current_progress >= len(self.password_sequence):
            return True, True, "密码已完成！"
        
        expected_shape = self.password_sequence[self.current_progress]
        
        # 识别当前图形
        detected_shape = detector.get_shape_by_name(image, expected_shape)
        
        if detected_shape and detected_shape["confidence"] > self.min_confidence:
            # 识别正确
            self.current_progress += 1
            self.failed_attempts = 0  # 重置失败次数
            
            if self.current_progress >= len(self.password_sequence):
                # 密码完成
                return True, True, "🎉 解锁成功！密码验证完成！"
            else:
                next_shape = self.password_sequence[self.current_progress]
                return True, False, f"✅ 正确！下一个图形: {self._get_shape_emoji(next_shape)}{next_shape}"
        else:
            # 识别错误或未识别到期望图形
            all_shapes = detector.detect_shapes(image)[1]
            
            if all_shapes:
                detected_names = [shape["name"] for shape in all_shapes]
                wrong_input = ", ".join(detected_names)
            else:
                wrong_input = "未识别到图形"
            
            self.failed_attempts += 1
            
            if self.failed_attempts >= self.max_attempts:
                # 锁定系统
                self.is_locked = True
                self.lock_timeout = current_time + PASSWORD_LOCK_CONFIG["lock_timeout"]  # 锁定30秒
                self.reset()
                return False, False, f"❌ 错误次数过多！系统已锁定30秒。检测到: {wrong_input}"
            else:
                remaining_attempts = self.max_attempts - self.failed_attempts
                expected_emoji = self._get_shape_emoji(expected_shape)
                return False, False, f"❌ 错误！期望: {expected_emoji}{expected_shape}，检测到: {wrong_input}。剩余尝试次数: {remaining_attempts}"

    def get_status(self):
        """获取密码锁状态"""
        current_time = time.time()
        if self.is_locked and current_time < self.lock_timeout:
            unlock_time = self.lock_timeout
            is_locked = True
        else:
            unlock_time = None
            is_locked = False
            # 解除锁定状态
            if self.is_locked:
                self.is_locked = False
        
        return {
            "sequence": self.password_sequence,
            "current_index": self.current_progress,
            "is_locked": is_locked,
            "unlock_time": unlock_time,
            "is_complete": self.current_progress >= len(self.password_sequence),
            "failed_attempts": self.failed_attempts,
            "max_attempts": self.max_attempts
        }
    
    def reset(self):
        """重置密码锁状态"""
        self.current_progress = 0
        self.failed_attempts = 0
        self.last_check_time = 0
        # 不重置锁定状态，让用户等待
    
    def force_reset(self):
        """强制重置（包括解除锁定）"""
        self.current_progress = 0
        self.failed_attempts = 0
        self.last_check_time = 0
        self.is_locked = False
        self.lock_timeout = 0
    
    def get_progress_info(self):
        """获取当前进度信息"""
        if self.is_locked:
            remaining_time = max(0, int(self.lock_timeout - time.time()))
            if remaining_time > 0:
                return {
                    "progress": self.current_progress,
                    "total": len(self.password_sequence),
                    "current_shape": None,
                    "status": "locked",
                    "message": f"系统锁定中，剩余时间: {remaining_time}秒"
                }
        
        if self.current_progress >= len(self.password_sequence):
            return {
                "progress": self.current_progress,
                "total": len(self.password_sequence),
                "current_shape": None,
                "status": "completed",
                "message": "密码验证完成！"
            }
        
        current_shape = self.password_sequence[self.current_progress]
        return {
            "progress": self.current_progress,
            "total": len(self.password_sequence),
            "current_shape": current_shape,
            "status": "in_progress",
            "message": f"请输入: {self._get_shape_emoji(current_shape)}{current_shape}"
        }
    
    def _get_shape_emoji(self, shape_name):
        """获取图形对应的emoji"""
        emoji_map = {
            "circle": "⭕",
            "triangle": "🔺",
            "square": "⬜",
            "rectangle": "▭"
        }
        return emoji_map.get(shape_name.lower(), "🔷")
    
    def get_sequence_display(self):
        """获取密码序列的显示字符串"""
        display = []
        for i, shape in enumerate(self.password_sequence):
            emoji = self._get_shape_emoji(shape)
            if i < self.current_progress:
                display.append(f"✅{emoji}")
            elif i == self.current_progress:
                display.append(f"🔄{emoji}")
            else:
                display.append(f"⏳{emoji}")
        
        return " → ".join(display)
    
    def change_password(self, new_sequence):
        """更改密码序列"""
        if not isinstance(new_sequence, list) or len(new_sequence) == 0:
            return False, "密码序列必须是非空列表"
        
        valid_shapes = ["circle", "triangle", "square", "rectangle"]
        for shape in new_sequence:
            if shape.lower() not in valid_shapes:
                return False, f"无效的图形名称: {shape}。支持的图形: {', '.join(valid_shapes)}"
        
        self.password_sequence = [shape.lower() for shape in new_sequence]
        self.force_reset()
        return True, f"密码已更改为: {' → '.join(new_sequence)}"
    
    def get_statistics(self):
        """获取统计信息"""
        return {
            "sequence_length": len(self.password_sequence),
            "current_progress": self.current_progress,
            "failed_attempts": self.failed_attempts,
            "max_attempts": self.max_attempts,
            "is_locked": self.is_locked,
            "completion_rate": (self.current_progress / len(self.password_sequence)) * 100
        }